package com.tanhua.service;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.constant.CacheKey;
import com.tanhua.domain.Admin;
import com.tanhua.exception.BusinessException;
import com.tanhua.interceptor.AdminHolder;
import com.tanhua.mapper.AdminMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private AdminMapper adminMapper;
    @Value("${tanhua.secret}")
    private String secret;
    /**
     * 把验证码真实值缓存到Redis里
     * @param code 验证码值
     * @param uuid 客户端提供的随机字符串，作为缓存验证码时的key
     */
    public void cacheCode(String code, String uuid) {
        redisTemplate.opsForValue().set(CacheKey.CODE_PREFIX+uuid,code, Duration.ofMinutes(5));
    }

    /**
     * 登录校验
     * @param username 帐号
     * @param password 密码
     * @param code 验证码
     * @param uuid 验证码的标识符
     */
    public ResponseEntity login(String username, String password, String code, String uuid) {
        //从redis中获取验证码
        String value = redisTemplate.opsForValue().get(CacheKey.CODE_PREFIX + uuid);
        //核对验证码，错误直接报错返回，正确在redis中删除验证码
        if (value == null || !value.equals(code)) {
            throw new BusinessException("验证码错误");
        }
        redisTemplate.delete(CacheKey.CODE_PREFIX + uuid);
        //校验账号和密码
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        wrapper.eq("password", SecureUtil.md5(password));
        Admin admin = adminMapper.selectOne(wrapper);
        if (admin == null) {
            throw new BusinessException("帐号或密码错误");
        }
        //生成token
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", admin.getId());
        claims.put("username", admin.getUsername());
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();
        //把用户信息存储到redis中
        redisTemplate.opsForValue().set(CacheKey.TOKEN_PREFIX + token, JSON.toJSONString(admin), Duration.ofHours(1));
        //构造返回值
        Map<String, Object> result = new HashMap();
        result.put("token", token);
        return ResponseEntity.ok(result);
    }

    /**
     *  展示用户基本信息
     * @return
     */
    public ResponseEntity getAdminInfo() {
        Admin admin = AdminHolder.getAdmin();

        //构造返回值
        Map<String, Object> result = new HashMap<>();
        result.put("id", admin.getId().toString());
        result.put("username", admin.getUsername());
        result.put("avatar", admin.getAvatar());
        return ResponseEntity.ok(result);
    }

    /**
     * 用户登出
     * @return
     */
    public ResponseEntity logout() {
        redisTemplate.delete(CacheKey.TOKEN_PREFIX + AdminHolder.getToken());
        return ResponseEntity.ok(null);
    }

}
